package com.oritsh.dicom.scu;

import org.dcm4che.data.Attributes;
import org.dcm4che.data.Tag;
import org.dcm4che.data.UID;
import org.dcm4che.io.DicomInputStream;
import org.dcm4che.io.DicomOutputStream;
import org.dcm4che.net.Association;
import org.dcm4che.net.PDVInputStream;
import org.dcm4che.util.SafeClose;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: zarra
 * Date: 14-2-6
 * Time: 下午2:48
 * Copyright Shanghai Orient Rain Information Technology Co.,Ltd.
 */
public class MemoryStore implements  DicomStreamStore{

    private Map<String,ByteArrayOutputStream> datas = new HashMap<>();

    @Override
    public void store(Association as, Attributes fmi, PDVInputStream data) throws IOException {
        String tsuid = UID.ExplicitVRLittleEndian;//fmi.getString(Tag.TransferSyntaxUID, UID.ExplicitVRLittleEndian);
        String iuid  = fmi.getString(Tag.MediaStorageSOPInstanceUID);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        DicomOutputStream out = new DicomOutputStream(outputStream,tsuid);
        try {
            out.writeFileMetaInformation(fmi);
            data.copyTo(out);
            datas.put(iuid,outputStream);

        } catch (Throwable e){
            e.printStackTrace();
            throw e;
        }finally {
            SafeClose.close(out);
        }

    }

    @Override
    public DicomInputStream fetch(String iuid) throws IOException {
        if (!datas.containsKey(iuid))
            return null;
        ByteArrayInputStream inputStream = new ByteArrayInputStream(datas.get(iuid).toByteArray());
        return new DicomInputStream(inputStream);
    }

    @Override
    public DicomInputStream pop(String iuid) throws IOException {
        DicomInputStream inputStream = fetch(iuid);
        datas.remove(iuid);
        return inputStream;
    }
}
